package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQuery;
import cn.wolfcode.service.IEmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Page<Employee> queryPage(EmployeeQuery qo) {
        Page<Employee> page = new Page<>(qo.getCurrentPage(),qo.getPageSize());
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        return super.page(page,wrapper);
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<String> selectByPermission(Long id) {
        return employeeMapper.selectByPermission(id);
    }

    @Override
    public Employee login(String username, String password) {
        List<Employee> employees = employeeMapper.selectList(null);
        if (!StringUtils.hasText(username)){
            throw new RuntimeException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)){
            throw new RuntimeException("用密码不能为空");
        }
        Employee loginEmp =null;
        for (Employee e:employees) {
            //用户名正确
            if (e.getName().equals(username)){
                //密码也正确
                if (e.getPassword().equals(password)){
                    //登录成功
                    loginEmp =e;
                }else {
                    //密码不正确
                    throw new RuntimeException("密码不正确");
                }
            }
        }
        if (loginEmp == null){
            throw  new RuntimeException("此用户不存在");
        }
        return loginEmp;
    }
}
